﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace iTool_Cetector
{
    public class HeartbeatMiddleware
    {
        private readonly RequestDelegate requestDelegate;
        public HeartbeatMiddleware(RequestDelegate requestDelegate)
        {
            this.requestDelegate = requestDelegate;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                string requestPath = context.Request.Path;

                Utils.Logger(context);

                //GlobalUtils.SeedString == null 理论上不能做任何事
                if (string.IsNullOrWhiteSpace(GlobalUtils.SeedString))
                {
                    return;
                }

                // 验证是否是Gateway连接
                //if (!string.IsNullOrWhiteSpace(GlobalUtils.SeedString))
                //{
                //    context.Request.Headers.TryGetValue("seed", out StringValues value);

                //    if (Decrypt(GlobalUtils.SeedString, value) != (GlobalUtils.GatewayUrl == "http://127.0.0.1:1994" ? "127.0.0.1" : GlobalUtils.PublicIp))
                //    {
                //        context.Response.StatusCode = 500;
                //        await context.Response.WriteAsync("error");
                //        return;
                //    }
                //}

                if (requestPath.ToLower() == "/heartbeat")
                {
                    context.Response.StatusCode = 200;
                    await context.Response.WriteAsync("h");
                    return;
                }

                await this.requestDelegate(context);
            }
            catch (Exception ex)
            {
                Utils.Logger("HeartbeatMiddleware", ex);
            }
        }

        public static string Decrypt(string Text, string sKey)
        {
            try
            {
                var des = DES.Create();
                int len;
                len = Text.Length / 2;
                byte[] inputByteArray = new byte[len];
                int x, i;
                for (x = 0; x < len; x++)
                {
                    i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                    inputByteArray[x] = (byte)i;
                }
                var summary = Md5HelperHash(sKey).ToUpper().Substring(0, 8);
                var summaryByte = Encoding.ASCII.GetBytes(summary);
                des.IV = des.Key = summaryByte;
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Encoding.Default.GetString(ms.ToArray());
            }
            catch
            {
                return string.Empty;
            }
        }

        public static string Md5HelperHash(string input)
        {
            var md5Hasher = MD5.Create();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
    }
}
